/*
 * @Author: szx
 * @Date: 2022-04-01 14:05:16
 * @LastEditTime: 2022-04-01 15:06:16
 * @Description:
 * @FilePath: \leetcode\1-99\76\76_2.js
 */
/**
 * @param {string} s
 * @param {string} t
 * @return {string}
 */
var minWindow = function (s, t) {
    const m = s.length;
    const window = {};
    for (let i of t) {
        if (window[i]) window[i]++;
        else window[i] = 1;
    }
    const len = Object.keys(window).length;
    let l = 0;
    let cnt = 0;
    let res = '';
    let min = Number.MAX_SAFE_INTEGER;
    for (let r = 0; r < m; r++) {
        const ch = s[r];
        if (window[ch] != null) {
            window[ch]--;
            if (window[ch] == 0) cnt++;
        }
        while (cnt == len && l <= r) {
            if (r - l + 1 < min) {
                res = s.substring(l, r + 1);
                min = r - l + 1;
            }
            if (window[s[l]] != null) {
                window[s[l]]++;
                if (window[s[l]] == 1) cnt--;
            }
            l++;
        }
        while (window[s[l]] == null && l < r) l++;
    }
    return res;
};
console.log(minWindow('a', 'a'));
console.log(minWindow('aaaaaaaaaaaabbbbbcdd', 'abcdd'));
console.log(minWindow('a', 'b'));
console.log(minWindow('ADOBECODEBANC', 'ABC'));
